<?php

namespace Home\Controller;

use Home\Controller\BaseController;

class PublicController extends BaseController {

    public function _initialize() {
        
    }

    //用户登录
    public function login() {
//        $strPhone = I("phone");
//        $vcode = I("vcode");
        $openid = I("wx_openid");
        $wx_headimgurl = I('wx_headimgurl');
        $wx_nickname = I('wx_nickname');
//        $os = I('os', 0, 'intval');

        $where = [];
        empty($openid) && $this->error("请传入微信openid");
//        empty($vcode) && $this->error("请输入验证码");
//        $vcode != S($strPhone) && $this->error("验证码错误");

        $where['u.wx_openid'] = $openid;

        $userInfo = M()->field("u.user_id,u.user_token,u.nick_name,u.head_imgurl,u.phone,u.create_time,u.status")
                        ->table("ot_users as u ")
                        ->where($where)->find();

        if (empty($userInfo)) {
            $newuser['wx_openid'] = $openid;
            $newuser['head_imgurl'] = $wx_headimgurl;
            $newuser['nick_name'] = $wx_nickname;

            M('Users')->add($newuser);
        }


        //$objUser = M('Users');
        $userInfo = M()->field("u.user_id,u.user_token,u.nick_name,u.head_imgurl,u.phone,u.create_time,u.status")
                        ->table("ot_users as u ")
                        ->where($where)->find();
        empty($userInfo) && $this->error('登录失败');

        if ($userInfo['status']) {
            $this->ajaxReturn(0, '您的账号已被禁用,请联系管理员', '', 110);
        }

        // $this->getUserStatus($userInfo['user_id']);
//        session('user_id', $userInfo['user_id']);
//        $date = strtotime($userInfo['create_time']);
//        $userInfo['create_time'] = date('Y-m-d', $date);


        $content = \Common\Util\Util::randStr(60, 2) . $openid . NOW_TIME . '123456';
        $userToken = \Common\Util\Util::encrypt($content);

        $data['user_token'] = $userToken;

        if (!empty($wx_headimgurl)) {
            $data['head_imgurl'] = $wx_headimgurl;
        }

        if (!empty($wx_nickname)) {
            $data['nick_name'] = $wx_nickname;
        }

        M('Users')->where(array('user_id' => $userInfo['user_id']))->save($data);

        //返回phpsessid
//        $userInfo['PHPSESSID'] = session_id();
        /*         * ******token 查询返回********************************************** */
//        $arrUserWhere['user_id'] = $userInfo['user_id'];
        $userInfo['user_token'] = $userToken;

        unset($userInfo['user_id']);
        /*         * ******token 查询返回********************************************** */
        $this->success("登录成功", $userInfo);
    }

    public function wxlogin() {
        $openid = I("wx_openid");
        $os = I('os', 0, 'intval'); //0 ios 1安卓
        $where['u.wx_openid'] = $openid;

        $userInfo = M()->field("u.user_id,u.user_token,u.nick_name,u.head_imgurl,u.phone,u.create_time,u.status")
                        ->table("ot_users as u ")
                        ->where($where)->find();

        if (!empty($userInfo)) {
            $content = \Common\Util\Util::randStr(60, 2) . $userInfo['phone'] . NOW_TIME . '123456';
            $userToken = \Common\Util\Util::encrypt($content);

            $data['user_token'] = $userToken;
            $data['os'] = $os;

            M('Users')->where(array('user_id' => $userInfo['user_id']))->save($data);
        }

        $this->success("登录成功", $userInfo);
    }

    //验证码发送
    public function sendCode() {
        $strPhone = I('phone');
        $type = I('type', 0, 'intval');
        empty($strPhone) && $this->error("请输入手机号");

        $objUser = M('Users');
        $userInfo = $objUser->where(array('phone' => $strPhone))->find();

        //1(注册)，2（找回密码）
        if ($type == 1) {
            //验证手机号是否存在
            if (!empty($userInfo)) {
                if (!empty($userInfo['wx_openid'])) {
                    $this->error("该手机号已被注册");
                    return;
                } else if ($userInfo['status'] == 1) {
                    $this->error("用户被禁用，无法使用", '', 110);
                    return;
                }
            }
        }
        if ($type == 2) {
            //验证手机号是否不存在
            if (empty($userInfo)) {
                $this->error("该手机未注册");
                return;
            }
        }

//        $strRand = createVerify($strPhone);
        //测试使用
        S($strPhone, '1234', 3600);
        $this->success("发送成功", 1234);
    }

    //忘记密码修改
    public function forgetPwd() {
        $strPhone = I('phone');
        $strPwd = I('password');
        $strCode = I('code', -1);
        empty($strPhone) && $this->ajaxReturn(0, "请输入手机号");
        empty($strPwd) && $this->ajaxReturn(0, "请输入密码");
        $strCode != S($strPhone) && $this->ajaxReturn(0, "验证码错误");

        $data['password'] = md5($strPwd);
        $res = M("Users")->where(array('phone' => $strPhone))->save($data);

        if ($res) {
            $this->success();
        } else {
            $this->ajaxReturn(0, '修改失败');
        }
    }

    //退出
    public function logout() {
        session_destroy();
        $this->success();
    }

    public function getRecmdDog() {
        $is_all = I('is_all', 0, 'intval');
        $num = 5;
        if ($is_all) {
            $num = 50;
        }
        $today = date('Y-m-d', time());
        $where .= " create_time between '$today 00:00:00' AND " . "'" . $today . ' 23:59:59' . "'";
        $dog_ids = M('Reward')->field('sum(number) as number,dog_id')->where($where)->group('dog_id')->limit(0, $num)->order('sum(number) desc')->select();

        $dog_list = [];

        foreach ($dog_ids as $id) {
            $dog = M('Dog')->field('dog_id,dog_name,dog_face')->where(['dog_id' => $id['dog_id']])->find();

            if ($dog['dog_face']) {
                $dog['dog_face'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $dog['dog_face'];
            }
            $dog['number'] = $id['number'];
            $dog_list[] = $dog;
        }

        $this->success('获取成功', $dog_list);
    }

    public function getRecmdTopic() {
        $is_all = I('is_all', 0, 'intval');
        $p = I('p', 0, 'intval');
        $size = 15;
        $page = 0;
        if ($is_all) {
            $size = I('psize', 15, 'intval');
            if ($p) {
                $page = $p * 15;
            }
        }

//        $topic_ids = M('TopicFollow')
//                        ->table('ot_topic_follow tf')
//                        ->join('right join ot_topic t on tf.topic_id = t.topic_id')
//                        ->field('count(tfollow_id) as follow_number,t.topic_id')
//                        ->where(['t.is_del' => 0])
//                        ->group('tf.topic_id')
//                        ->limit($page, $size)
//                        ->order('count(tfollow_id) desc')->select();
        
        $topic_ids =  M('Topic')
                        ->table('ot_topic t')
                        ->field('t.topic_id')
                        ->where(['t.is_del' => 0])
                        ->limit($page, $size)
                        ->select();

        $topic_list = [];
        foreach ($topic_ids as $id) {
            
            $topic_info = M('Topic')->where(['topic_id' => $id['topic_id']])->find();
            $id['follow_number'] = M('TopicFollow')->where(['topic_id' => $id['topic_id']])->count();
            $id['topic_name'] = $topic_info['topic_name'];
            $id['follow_face'] = M()->table('ot_topic_follow tf')
                    ->join('left join ot_users u on tf.user_id = u.user_id')
                    ->where(['tf.topic_id' => $id['topic_id']])
                    ->limit(0, 4)
                    ->getField('head_imgurl', true);
            $id['topic_content'] = $topic_info['topic_content'];
            $id['topic_pic'] = 'https://' . $_SERVER['HTTP_HOST'] . __ROOT__ . $topic_info['topic_pic'];
            $id['post_num'] = M('Post')->where(['topic_id' => $id['topic_id']])->count();
            $topic_list[] = $id;
        }
        
        list_sort_by($topic_list, 'post_num','desc');
        $this->success('获取成功', $topic_list);
    }

    public function getArea() {
        $fid = I('fid', 0, 'intval');
        $list = M('Area')->where(['fid' => $fid])->select();

        $this->success('获取成功', $list);
    }

    public function getUserInfoById() {
        $id = I('id', 0, 'intval');

        if ($id == 0) {
            $this->error('请传入ID');
        }

        $info = M('Users')->field('user_id,head_imgurl,nick_name')->where(['user_id' => $id])->find();

        $this->success('获取成功', $info);
    }

    public function getOpenId() {
        $appid = 'wx30752703b6104080';
        $appSec = '662313ab979c197f150eece00a3bfeef';
        $code = I('code');

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $appSec . '&js_code=' . $code . '&grant_type=authorization_code';

        $info = file_get_contents($url); //发送HTTPs请求并获取返回的数据，推荐使用curl  
        $json = json_decode($info); //对json数据解码  
        $arr = get_object_vars($json);
        $openid = $arr['openid'];

        $this->success('获取成功', $arr);
    }

    public function getQcode() {
        $filename = md5(time() . mt_rand(10, 99)) . ".png"; //新图片名称

        $imgDir = './Uploads/Qcode/';
        $newFilePath = $imgDir . $filename;

        $access_token = S('access_token');
        if (!$access_token) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx30752703b6104080&secret=662313ab979c197f150eece00a3bfeef";
            $res = json_decode(file_get_contents($url));
            $access_token = $res->access_token;
            if ($access_token) {
                S('access_token', $access_token, 7000);
            }
        }

        $getUlr = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" . $access_token;

//        $getUlr = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=" . $access_token;
        $toPage = 'pages/dcDetails/dcDetails?id=1';

//        echo $getUlr;die;
        $data['path'] = $toPage;

        $res = $this->post($getUlr, json_encode($data));


        file_put_contents($newFilePath, $res);
        $src_path = yuan_img('./Uploads/Picture/2017-11-27/3456789.jpg');
        watermarklogo($newFilePath, $src_path);
  
    }

    public function post($url, $post_data = '', $timeout = 5) {

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_POST, 1);

        if ($post_data != '') {

            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        }

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

        curl_setopt($ch, CURLOPT_HEADER, false);

        $file_contents = curl_exec($ch);

        curl_close($ch);

        return $file_contents;
    }

}
